<!-- components/charts/NumberChart.vue -->
<template>
  <div class="number-chart" :style="{ height: height }">
    <div v-if="!hasValidData" class="empty-number">
      <el-empty description="暂无数据" :image-size="100">
      </el-empty>
    </div>
    <div v-else class="number-content">
      <div class="number-title">{{ props.config.title || '指标' }}</div>
      <div class="number-value" :style="{ fontSize: numberOption.fontSize + 'px' }">
        {{ displayValue }}
        <span v-if="numberOption.unit" class="number-unit">{{ numberOption.unit }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  height: {
    type: String,
    default: '100%'
  },
  config: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['refresh'])

// 获取数字图表配置
const numberOption = computed(() => props.config.option || {})

// 检查是否有有效数据
const hasValidData = computed(() => {
  const data = props.data || {}
  const valueField = numberOption.value.valueField

  if (Object.keys(data).length === 0 || !valueField) {
    return false
  }

  const value = data[valueField]

  if (value === null || value === undefined || value === '') {
    return false
  }

  if (Array.isArray(value) && value.length === 0) {
    return false
  }

  return true
})

// 计算显示的数值
const displayValue = computed(() => {
  if (!hasValidData.value) return '-'

  const valueField = numberOption.value.valueField
  const value = props.data[valueField]
  let numericValue = 0

  // 提取数值
  if (typeof value === 'number') {
    numericValue = value
  } else if (Array.isArray(value) && value.length > 0) {
    const firstValue = value[0]
    numericValue = typeof firstValue === 'number' ? firstValue : parseFloat(firstValue) || 0
  } else if (typeof value === 'string') {
    numericValue = parseFloat(value) || 0
  } else {
    numericValue = parseFloat(value) || 0
  }

  // 格式化小数位数
  return numericValue.toFixed(numberOption.value.decimalPlaces)
})
</script>

<style scoped>
.base-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.empty-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #fafafa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}
</style>